package com.jxc.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.Brand;
import com.jxc.model.po.Discount;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.RepertoryBrand;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.VBrand;
import com.jxc.service.BrandServiceI;

@Service("brandService")
public class BrandServiceImpl implements BrandServiceI {

		@Autowired
	private BaseDaoI<Brand> brandDao;
	@Autowired
	private BaseDaoI<RepertoryBrand> repertoryBrandDao;
	@Autowired
	private BaseDaoI<Repertory> repertoryDao;
	@Autowired
	private BaseDaoI<User> userDao;
	@Autowired
	private BaseDaoI<Discount> discountDao;
	
	@Override
	public List<VBrand> combobox(VBrand vbrand) {
		return this.changeModel(findCombobox(vbrand));
	}

	public DataGrid datagrid(VBrand vbrand) {
		DataGrid dg = new DataGrid();
		List<VBrand> b = this.findlist(vbrand);
		dg.setRows(b);
		dg.setTotal(this.total(vbrand));
		return dg;
	}
	public List<VBrand> findlist(VBrand vbrand) {
		List<VBrand> b = this.changeModel(this.find(vbrand));
		return b;
	}

	public void delete(String ids) {
		System.out.println(ids);
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					Brand brand = brandDao.get(Brand.class, Long.parseLong(id
							.trim()));
					if (brand != null) {
						brand.setIsDelete(true);
						brandDao.update(brand);
					}
				}
			}
		}
	}

//	@Override
	public void save(VBrand vbrand) {
		Brand ba = new Brand();
		ba.setName(vbrand.getName());
		ba.setRemark(vbrand.getRemark());
		ba.setIsDelete(false);
		if(vbrand.getDid()!=null){
			Discount dis = discountDao.get(Discount.class, vbrand.getDid());
			ba.setDiscount(dis);
		}if(vbrand.getUid()!=null){
		   User uu = userDao.get(User.class, vbrand.getUid());
		   if(uu.getUserType()==3||uu.getUserType()==4){
			   if(uu.getUser()!=null){
				   ba.setUser(uu.getUser());
			   }
		   }else{
			   ba.setUser(uu);
		   }
		}
		brandDao.save(ba);
		
		for (String id : vbrand.getRid1().split(",")) {
			RepertoryBrand repertorybrand = new RepertoryBrand();
			repertorybrand.setRepertory(repertoryDao.get(Repertory.class, Long.valueOf(id.trim())));
			repertorybrand.setBrand(ba);
			repertoryBrandDao.save(repertorybrand);
		}
		
	}
	
	
	public void update(VBrand vbrand) {
		try {
			Brand brand = brandDao.get(Brand.class, vbrand.getId());
			BeanUtils.copyProperties(vbrand, brand,
					new String[] { "id", "isDelete" });
			if(vbrand.getDid()!=null){
				brand.setDiscount(new Discount(vbrand.getDid()));
			}
			this.brandDao.update(brand);
			System.out.println(vbrand.getRid1());
			if(vbrand.getBrids()!=null){
				for (String brid : vbrand.getBrids().split(",")) {
					RepertoryBrand rBrand = repertoryBrandDao.get(RepertoryBrand.class, Long.valueOf(brid.trim()));
					repertoryBrandDao.delete(rBrand);
				}
				if (vbrand.getRid1() != null) {
					for (String id : vbrand.getRid1().split(",")) {
						RepertoryBrand repertorybrand = new RepertoryBrand();
						repertorybrand.setRepertory(repertoryDao.get(Repertory.class, Long.valueOf(id.trim())));
						repertorybrand.setBrand(brand);
						repertoryBrandDao.saveOrUpdate(repertorybrand);
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

	private List<VBrand> changeModel(List<Brand> brands) {
		List<VBrand> vbrands = new ArrayList<VBrand>();
		if (brands != null && brands.size() > 0) {
			for (Brand brand : brands) {
				VBrand vbrand = new VBrand();
				BeanUtils.copyProperties(brand, vbrand);
				if(brand.getRepertoryBrandList()!=null){
					String rid = "";
					String rname = "";
					String brid = "";
					for(RepertoryBrand rb: brand.getRepertoryBrandList()){
						if(rb.getRepertory().getIsDelete()==false){
							brid += rb.getId()+",";
							rid += rb.getRepertory().getId()+",";
							rname += rb.getRepertory().getName()+",";
						}
					}
					
					if(rid.length()>1){
						vbrand.setBrids(brid.substring(0,brid.length()-1));
						vbrand.setRid1(rid.substring(0, rid.length()-1));
						vbrand.setRname1(rname.substring(0, rname.length()-1));
					}
				}
				if(brand.getDiscount()!=null){
					Discount dis = brand.getDiscount();
					vbrand.setDid(dis.getId());
					vbrand.setDname(dis.getDiscountNum());
				}
				vbrands.add(vbrand);
			}
		}
		return vbrands;
	}
	private List<Brand> findCombobox(VBrand vbrand) {
		String hql = "from Brand t where 1=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vbrand, hql, values);
		
		hql += " order by t.name " ;	
		return brandDao.find(hql, values);
	}
	
	private List<Brand> find(VBrand vbrand) {
////		String hql = "select t from Brand t join RepertoryBrand rb on t.id=rb.brand.id join Repertory r on r.id=rb.repertory.id where 1=1 ";
//		List<Brand> bs = new ArrayList<Brand>();
//
//		String hql = "select t from Brand as t join t.repertoryBrandList as rbl join rbl.repertory as r where 1=1";
//		try{
//			List<Object> values = new ArrayList<Object>();
//	    	hql = addWhere(vbrand, hql, values);
//
////			if (vbrand.getSort() != null && vbrand.getOrder() != null) {
////				hql += " group by t." + vbrand.getSort() ;
////			}	
//			
//	    	bs = 
//	    	System.out.println(bs.toString());
//		}catch(Exception e){
//			e.printStackTrace();
//		}
		String hql = "select t from Brand as t join t.repertoryBrandList as rbl join rbl.repertory as r where 1=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vbrand, hql, values);
		
		hql += " order by t.name " ;	
		return brandDao.find(hql, values, vbrand.getPage(), vbrand.getRows());
	}

	private Long total(VBrand vbrand) {
		Long t = 0l;
		try {
			String hql = " select count(*) from" +
					" (select  count(*) from spgl_brand sb,rkgl_repertory_brand rb,rkgl_repertory r " +
					" where sb.id=rb.brand_id and r.id=rb.repertory_id and sb.is_delete=0 " ;
				
			if (vbrand.getName() != null && !vbrand.getName().trim().equals("")) {
				hql += " and sb.name like  "+"'%" + vbrand.getName().trim() + "%'";
			}
			if (vbrand.getUid() != null) {
				hql += " and sb.user_id = "+vbrand.getUid();
			}
			if (vbrand.getRname() != null&& !vbrand.getRname().trim().equals("")) {
				hql += " and r.name like "+"'%"+vbrand.getRname()+"%'";
			}if(vbrand.getRid()!=null){
				hql += " and r.id = "+vbrand.getRid();
			}
			hql += " group by sb.id)aa ";
			BigInteger a = this.repertoryBrandDao.countSQL(hql);
			t = a.longValue();
		} catch (Exception e) {
			e.printStackTrace();
		}		
		
		return  t;
	}

	private String addWhereTotal(VBrand vbrand, String hql, List<Object> values) {
		
		return hql;
	}
	
	private String addWhere(VBrand vbrand, String hql, List<Object> values) {
		if (vbrand.getName() != null && !vbrand.getName().trim().equals("")) {
			hql += " and t.name like ? ";
			values.add("%%" + vbrand.getName().trim() + "%%");
		}
		if (vbrand.getUid() != null) {
			hql += " and t.user.id = ?";
			values.add(vbrand.getUid());
		}
		if (vbrand.getRname() != null&&!vbrand.getRname().equals("")) {
			hql += " and r.name like ?";
			values.add("%%"+vbrand.getRname()+"%%");
		}
		if(vbrand.getRid()!=null){
			hql += " and r.id = ?";
			values.add(vbrand.getRid());
		}
		hql += " and t.isDelete = 0 group by t.id";
		return hql;
	}

	@Override
	public Object findDiscountNum(Long id) {
		Brand ba = brandDao.get(Brand.class, id);
		List<Brand> bList = new ArrayList<Brand>();
		bList.add(ba);
		return this.changeModel(bList);
	}

	

}
